package com.parktech.sun.domain.service.specialtopic.impl;

import com.parktech.sun.domain.model.specialtopic.SpecialTopic;
import com.parktech.sun.domain.model.specialtopic.SpecialTopicCategory;
import com.parktech.sun.domain.repository.Page;
import com.parktech.sun.domain.repository.specialtopic.SpecialTopicRepository;
import com.parktech.sun.domain.service.impl.BaseServiceImpl;
import com.parktech.sun.domain.service.specialtopic.SpecialTopicService;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Property;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * User: Think
 * Date: 11-1-12
 * Time: 下午7:56
 */
@Service("specialTopicService")
public class SpecialTopicServiceImpl extends BaseServiceImpl<SpecialTopic> implements SpecialTopicService {

    private SpecialTopicRepository specialTopicRepository;

    @Autowired
    public SpecialTopicServiceImpl(SpecialTopicRepository specialTopicRepository) {
        super(specialTopicRepository);
        this.specialTopicRepository = specialTopicRepository;
    }

    public SpecialTopicCategory getByCategoryId(Long specialTopicCategoryId) {
        return specialTopicRepository.getCategoryById(specialTopicCategoryId);
    }

    public Page searchCategory(String title , Page page) {

        Criteria criteria = specialTopicRepository.createCriteria(SpecialTopicCategory.class);

        if (StringUtils.isNotEmpty(title)) {
            criteria.add(Property.forName("title").like(title, MatchMode.ANYWHERE));
        }
        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("modifyTime"));

        return specialTopicRepository.page(criteria, page);
    }

    public void saveOrUpdateCategory(SpecialTopicCategory specialTopicCategory) {
        specialTopicRepository.saveOrUpdateCategory(specialTopicCategory);
    }

    public Page search(String title, Long category, Integer publishStatus, Page page) {

        Criteria criteria = specialTopicRepository.createCriteria();

        if (StringUtils.isNotEmpty(title)) {
            criteria.add(Property.forName("title").like(title, MatchMode.ANYWHERE));
        }

        if (category != null && category != -1L) {
            criteria.add(Property.forName("category.id").eq(category));
        }

        if (publishStatus != -1) {
            criteria.add(Property.forName("publishStatus").eq(publishStatus));
        }

        criteria.addOrder(Order.desc("orderCode"));
        criteria.addOrder(Order.desc("publishDate"));
        criteria.addOrder(Order.desc("modifyTime"));

        return specialTopicRepository.page(criteria, page);

    }
}
